import React, {Fragment} from 'react';
import { connect } from 'dva';
import { Card, Button, Form, Input, Row, Col, message,Spin,Popover,Icon,Modal, Steps,List} from 'antd';
import HeaderTab from '@/components/HeaderTab';
import router from 'umi/router';
import styles from './index.less';
import Modalsion from './modal';
import { abs } from '@/utils/utils';

const FormItem = Form.Item;

@Form.create()
class CouponComponent extends React.Component {
    constructor() {
        super();
        this.state={
            colheight: '280px',
            dataSource:[],
            loading: false,
            valueLoading: false,
            showData: false,
            btnLoaidng: false,
            detail: {},
            visible: false,
            tabs: [
                {
                    title: '自提管理',
                    key: `/${window.storeId}/order/pickedUp/${'0'}`,
                },
                {
                    title: '自提核销',
                    key: `/${window.storeId}/order/pickUpVerification`,
                },
            ],
        }
    }

    componentWillMount() {
        window.Isoption = false;
      }
      componentDidMount() {
        window.Isoption = true;
      }

   // 头部状态切换
   onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };

    handleSearch =e => {
        e.preventDefault();
        const {form, dispatch} = this.props;
        this.setState({
            loading: true,
            btnLoaidng: true,
        })
        form.validateFields((err, values) => {
            if(err) return;
            dispatch({
                type: 'orderPickUp/GetSelfFetchOrder',
                payload: {
                    DeveryCode: values.DeveryCode
                },
                callBack: {
                    success: res=> {
                        if(res.Code ===0) {
                            this.setState({
                                showData: 'success',
                                detail: res.Data,
                                loading: false,
                                btnLoaidng: false
                            })
                        } else {
                            this.setState({
                                showData: 'err',
                                loading: false,
                                btnLoaidng: false
                            })
                        }
                    },
                    error: res=> {
                        this.setState({
                            showData: 'err',
                            loading: false,
                            btnLoaidng: false
                        })
                    }
                }
            })
        })
    }

    //核销
    clickSure =(OrderNo) => {
        const {dispatch} = this.props;
        const that = this;
        Modal.confirm({
            title: '确认核销该订单',
            okText: '确认',
            cancelText: '取消',
            onOk: ()=> {
                dispatch({
                    type: 'orderPickUp/SetFinishOrder',
                    payload: {
                        OrderNo:OrderNo
                    },
                    callBack: {
                        success: res=> {
                            if(res.Code ===0) {
                                message.success('核销成功');
                                that.referch();
                            } else {
                                message.error('核销失败')
                            }
                        }
                    }
                })
            }
        });
    }

    //刷新事件
    referch =()=> {
        const {dispatch} = this.props;
        dispatch({
            type: 'orderPickUp/GetSelfFetchOrder',
            payload: {
                DeveryCode: this.state.codeValue
            },
            callBack: {
                success: res=> {
                    if(res.Code ===0) {
                        this.setState({
                            showData: 'success',
                            detail: res.Data,
                            loading: false,
                            btnLoaidng: false
                        })
                    } else {
                        this.setState({
                            showData: 'err',
                            loading: false,
                            btnLoaidng: false
                        })
                    }
                },
                error: res=> {
                    this.setState({
                        showData: 'err',
                        loading: false,
                        btnLoaidng: false
                    })
                }
            }
        })
    }

    //刷新
    clickSureAgan=()=> {       
        this.setState({
            loading: true
        })
       this.referch();
    }

    //标记收款
    clickSureMark=(orderNo)=> {
        const {dispatch} = this.props;
        const that = this;
        Modal.confirm({
            title: '请确认已收取货款，标记收款后状态将无法返回',
            okText: '确认',
            cancelText: '取消',
            onOk: ()=> {
                dispatch({
                    type: 'orderdetail/MarkedReceipt',
                    params: {
                      OrderNo: orderNo
                    },
                    callBack: {
                      success: res => {
                        if (res.Code === 0) {
                          message.success('操作成功');
                          that.referch();
                        }
                      },
                      error: res => {
                        console.log(res)
                        message.error('操作失败');
                      }
                    },
               })
            }
        });
    }

    inputChange=(e) =>{
        this.setState({
            codeValue: e.target.value
        })
    }

    showModal=()=> {
        const title="扫一扫核销";
        const width = 640;
        this.showModalsion.show({width, title})
    }

    renderForm() {
        const {form: { getFieldDecorator },loading1} = this.props;
        const {btnLoaidng} = this.state;

        return (
          <Form  layout="inline">
            <Row >
              <Col span={8}>
                <FormItem label="提货码">
                  {getFieldDecorator('DeveryCode',
                    // {initialValue: '190425190245869965'}
                  )(
                    <Input className="xkd-width-per-100" onChange={e => this.inputChange(e)}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <Button type="primary" onClick={this.handleSearch} loading={btnLoaidng}>
                    核销
                </Button>
              </Col>
              <Col span={8} style={{textAlign: 'right', marginTop: 4}}>
                <a onClick={this.showModal}>
                    扫一扫核销
                </a>
              </Col>
            </Row>
          </Form>
        );
    }

    renderItem(detail) {
        let refund =null;
        detail.OrderItems.ActiveRefundList&&detail.OrderItems.ActiveRefundList.forEach((item)=> {
            refund = item.Status.indexOf('退款中')> -1? true: false
        })
        if(detail.HasPayed) {
            if(refund) {
                return (
                    <div style={{paddingLeft: 40}}>
                        <div className={styles.headText}>订单退款中,无法核销</div>
                        <Button disabled>确认核销</Button>
                    </div>
                )
            } else {
                if (detail.OrderStatus===3) { //待核销
                    return (
                        <div style={{paddingLeft: 40}}>
                            <div className={styles.headText}>订单已付款，等待核销</div>
                            <Button type="primary" onClick={()=>this.clickSure(detail.OrderNo)}>确认核销</Button>
                        </div>
                    )
                }
                if (detail.OrderStatus===5) { //已核销
                    return (
                        <div style={{paddingLeft: 40}}>
                            <div className={styles.headText}>订单已核销</div>
                            <p>核销时间：{detail.FinishTime}</p>
                        </div>
                    )
                }
            }
        } else {
            return (
                <div style={{paddingLeft: 40}}>
                    <div className={styles.headText} style={{color: 'red'}}>订单未付款,请与买家协商收取货款</div>
                    <div>
                        <Button onClick={()=>this.clickSureMark(detail.OrderNo)}>标记收款</Button>
                        <Button onClick={()=>this.clickSureAgan(detail.OrderNo)} style={{marginLeft: 8, marginRight: 8}}>刷新状态</Button>
                        <Popover
                            content={
                                <div>买家可继续通过小程序付款；买家付款后<br/>您需要点击"刷新状态"按钮刷新页面状态</div>
                            }
                            trigger="hover"
                            placement="right"
                        >
                            <Icon type="question-circle" style={{color: '#8c8c8c'}}/>
                        </Popover>
                    </div>
                </div>
            )
        }
    }

    render() {
        const {tabs, loading, activeId,showData,detail} = this.state;
        const {oemInfo} = this.props;
        return(
            <Fragment>
                {/* <HeaderTab
                    _this={this}
                    type="slider"
                    activeId={activeId}
                    onChange={this.onTabChange}
                    tabs={tabs}
                    >
                </HeaderTab> */}
                    <Card bordered={false}>
                        <div style={{
                                background:'#fafafa',
                                marginBottom:16,
                                paddingTop:16,
                                paddingRight:16,
                                boxSizing:'border-box',
                                marginTop: 16
                            }}>
                            <div className="tableListForm">{this.renderForm()}</div>
                        </div>
                        <div className={styles.loadingBox}>
                            <Spin spinning={loading}>
                                {showData ==='err' &&(
                                    <div style={{paddingLeft: 114}}>
                                        <Icon type="exclamation-circle" style={{color: 'red',marginRight: 8}}/>
                                        此提货码无效
                                    </div>
                                )}
                                 {showData ==='success' &&(
                                   <div>
                                       <Card className={styles.Details} bordered={false}>
                                          <Row>
                                            <Col span={8} style={{ height: this.state.colheight }} className={styles.borderleft}>
                                              <div className={styles.headText}>买家信息</div>
                                              <p>提货人: <span>{detail && detail.ReceiverAddress?detail.ReceiverAddress.Receiver:'-'}</span></p>
                                              <p>联系方式: <span>{detail && detail.ReceiverAddress?detail.ReceiverAddress.ReceiverPhone:'-'}</span></p>
                                              <p className={styles.address}>
                                                  <div>自提地点:</div>
                                                  <span>{detail && detail.PickupAddress.FullAddress}</span>
                                              </p>
                                              <p>订单编号: {detail && detail.OrderNo}</p>
                                              <p>付款方式: {detail && detail.PaymentChannelNameStr}</p>
                                              <p className="xkd-text-ellipsis2">买家留言: {detail &&detail.Remark?detail.Remark:'-'}</p>
                                              </Col>
                                              <Col span={16} style={{ height: this.state.colheight }} className={styles.border}>
                                                  {this.renderItem(detail)}
                                              </Col>
                                          </Row>
                                        </Card>
                                        <Card bordered={false} className={styles.Goods}>
                                          <Row className={styles.GoodsTitle}>
                                            <Col span={8}>商品信息</Col>
                                            <Col span={2}>价格</Col>
                                            <Col span={2}>数量</Col>
                                            <Col span={2}>优惠</Col>
                                            <Col span={3}>商家改价</Col>
                                            <Col span={3}>小计</Col>
                                            <Col span={4}>状态</Col>
                                          </Row>
                                          <List
                                            itemLayout="vertical"
                                            size="large"
                                            dataSource={detail && detail.OrderItems ? detail.OrderItems : []}
                                            renderItem={item => (
                                              <List.Item key={item.Id}>
                                                {
                                                 <Fragment>
                                                    <Row>
                                                      <Col span={8}>
                                                        <img src={`${oemInfo.cdnUrl}/${item.ThumbnailUrl}`} />
                                                        <p className="xkd-text-ellipsis2">{item.ProductName}</p>
                                                        <span>{item.SkuName}</span>
                                                      </Col>
                                                      <Col span={2}>￥{item.SingleFee}</Col>
                                                      <Col span={2}>{item.BuyNum}</Col>
                                                      <Col span={2}>{item.DiscountFee ? item.DiscountFee : '-'}</Col>
                                                      <Col span={3}>￥{item.ModifyProductFee}</Col>
                                                      <Col span={3}>￥{item.SubtotalFee}</Col>
                                                      <Col span={4}> {item.RightsStatus === 0 ? item.StatusName : <span>{item.RightsStatusName}</span>}</Col>
                                                    </Row>
                                                    {
                                                      item.Message ? <Row className="msg">
                                                        {
                                                          <Col>
                                                            {
                                                              item.Message.map((value, index) => {
                                                                return <p key={index}>{value.Name}：{value.text}</p>
                                                              })
                                                            }
                                                          </Col>
                                                        }

                                                      </Row> : null
                                                    }
                                                  </Fragment>
                                                }
                                              </List.Item>
                                            )}
                                          />
                                          <Row className="total">
                                          <Col>
                                                <div className="price">
                                                    <div>
                                                        <p>商品总价：</p>
                                                        <span>￥{detail && abs(detail.ProductFee, 2)}</span>
                                                    </div>
                                                    <div>
                                                        <p>运费：</p>
                                                        <span>￥{detail && abs(detail.OrderPayFreightAmount,2)}</span>
                                                    </div>
                                                    {detail && detail.DiscountFee!=0&&<div>
                                                        <p>优惠：</p>
                                                        <span>￥{detail && abs(detail.DiscountFee,2)}</span> 
                                                    </div>}
                                                    {detail && detail.ModifiedProductFee!=0&&<div>
                                                        <p>商品调价：</p>
                                                        <span>￥{detail && abs(detail.ModifiedProductFee,2)}</span>
                                                    </div>}
                                                    <div>
                                                        <p>订单金额：</p>
                                                        <span style={{color: '#F5222D'}}>￥{detail && abs(detail.OrderPayAmount,2)}</span>
                                                    </div>
                                                </div>
                                            </Col>
                                          </Row>
                                        </Card>
                                   </div>
                                )}
                            </Spin>
                        </div>
                    </Card>
                    <Modalsion
                        ref={e => {
                            this.showModalsion = e
                        }}
                    />
            </Fragment>

        )
    }
}

export default connect(({ marketing,global, loading }) => ({
    marketing,
    oemInfo:global.oemInfo,
    loading1: loading.effects['orderPickUp/GetSelfFetchOrder'],
    loading2: loading.effects['orderPickUp/SetFinishOrder'],
  }))(CouponComponent)
